package xiaojian.toolkit.netty.handler.codec.http;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.ssl.SslHandler;
import io.netty.util.ReferenceCountUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import xiaojian.toolkit.ebus.EventBus;

@ChannelHandler.Sharable
public class HttpResponseHandler extends ChannelInboundHandlerAdapter {
	private static Logger logger = LoggerFactory
			.getLogger(HttpResponseHandler.class);

	private EventBus eventBus;
	private String eventResponseReceived;

	private boolean useSsl;

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		logger.debug("fire event {} : {}", eventResponseReceived, msg);
		eventBus.fireEvent(eventResponseReceived, msg);
		
		// TODO -- 释放？
		ReferenceCountUtil.release(msg);
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		if (useSsl) {
			SslHandler sslHandler = ctx.pipeline().get(SslHandler.class);
			sslHandler.handshakeFuture();
		}

		ctx.fireChannelActive();
	}

	public String getEventResponseReceived() {
		return eventResponseReceived;
	}

	public void setEventResponseReceived(String eventResponseReceived) {
		this.eventResponseReceived = eventResponseReceived;
	}

	public void setEventBus(EventBus eventBus) {
		this.eventBus = eventBus;
	}
}
